﻿using Microsoft.Office.Core;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CloudStorageLight.DesktopTool
{
    public class ExcelImageConverter : DocumentImageConverter
    {
        public ExcelImageConverter()
        {
        }

        public override bool ToXpsFile(string inputFile, string outputPatternFile, int pageSize)
        {
            var excelApplication = new Microsoft.Office.Interop.Excel.Application();
            
            excelApplication.ScreenUpdating = false;
            Microsoft.Office.Interop.Excel.Workbook book = null;
            var xpsfile = GetExtnsionFilename(outputPatternFile, "xps");
            var outfile = GetExtnsionFilename(outputPatternFile, "jpg");
            try
            {
                book = excelApplication.Workbooks.Open(inputFile,
                    Type.Missing, true, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, 
                    Microsoft.Office.Interop.Excel.XlCorruptLoad.xlNormalLoad);
                book.ExportAsFixedFormat(
                    Microsoft.Office.Interop.Excel.XlFixedFormatType.xlTypeXPS,
                    GetExtnsionFilename(outputPatternFile, "xps"),
                    Type.Missing, Type.Missing, Type.Missing, Type.Missing, pageSize > 0 ? pageSize : Type.Missing);
                return true;
            }
            finally
            {
                if (book != null)
                {
                    object opt1 = Microsoft.Office.Interop.Excel.XlSaveAction.xlDoNotSaveChanges;
                    book.Close(false);
                    book = null;
                }
                if (excelApplication != null)
                {
                    excelApplication.Quit();
                    excelApplication = null;
                }

                GC.Collect();
                GC.WaitForPendingFinalizers();
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }

        }

    }
}

